import rnToAndroid from '../native/index'
/**
 * API 请求
 */
let baseUrl = 'http://unviewable.eicp.net/';  //服务器地址
let token = '';   

function apiFetch (method, url, params) {
    let headers = {
        "Content-Type": "application/json;charset=UTF-8",
        "accesstoken":token  //用户登陆后返回的token，某些涉及用户数据的接口需要在header中加上token
    };
    url = baseUrl + url;
    console.log("==========发起请求(start)============")
    console.log("====url===="+url)
    console.log("====method===="+method)
    console.log("====body===="+(method === 'POST' ? params : null))
    console.log("==========发起请求(end)============")
    return new Promise(function (resolve, reject) {  
        fetch(url, {  
              method: method,  
              headers: headers,  
              body: method === 'POST' ? params : null,  
            }) 
            .then((response) => { 
                console.log("==========返回数据(start)============")
                console.log("====response===="+response)
                console.log("==========返回数据(end)============")
                if (response.ok) {  
                    return response.json();  
                } else {  
                    reject({status:response.status})  
                }  
            })  
            .then((response) => {  
                resolve(response);  
            })  
            .catch((err)=> {
                reject({status:-1});  
            })  
        }
    ) 
}
// 返回在fetch模板中的调用接口
export default {
    get: function (url) {
      return apiFetch('GET', url)
    },
    post: function (url, params) {
        if(params){
            rnToAndroid.encode3Des(params).then((data)=> { 
                return apiFetch('POST', url, data)
            }, (code, message)=> {
                alert(message);
            });
        }else{
            return apiFetch('POST', url, params)
        }
    }
  }